var express = require("express");
var router = express.Router();
// 配置图片上虚拟路由
router.use("/upload", express.static("upload"));

var { DepartmentModel } = require("../model/model");

// 添加部门
router.post("/add_department", async (req, res) => {
  let body = req.body;
  await DepartmentModel.create(body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

// 修改部门
router.put("/edit_department/:id", async function (req, res) {
  let body = req.body;
  await DepartmentModel.updateOne({ _id: req.params.id }, { $set: body });
  res.send({
    code: 200,
    msg: "修改成功",
  });
});

// 删除部门
router.delete("/del_department/:id", async function (req, res) {
  await DepartmentModel.deleteOne({ _id: req.params.id });
  res.send({
    code: 200,
    msg: "删除成功",
  });
});

// 部门列表
router.get("/department_list", async (req, res) => {
  let pageIndex = req.query.pageIndex;
  let pageSize = req.query.pageSize;
  let username = req.query.username;
  let name = req.query.name;
  console.log(req.query);
  let list = [];
  let total = 0;
  let usernamereg = new RegExp(username, "i");
  let namereg = new RegExp(name, "i");
  list = await DepartmentModel.find({
    $and: [{ name: namereg }],
  })
    .populate("department_id")
    .populate("station_id")
    .skip((pageIndex - 1) * pageSize)
    .limit(pageSize)
    .sort({ times: -1 })
    .exec();
  total = list.length;
  res.send({
    code: 200,
    msg: "展示成功",
    data: list,
    total: total,
  });
});

module.exports = router;
